<template>
  <view class="flex-column w100" style="min-height: 100vh">
    <!-- #ifndef MP-TOUTIAO -->
    <uni-nav-bar style="z-index:999;" left-icon="left" @clickLeft="goBack" :title="user.username" :fixed="true"
      :statusBar='!isWin'></uni-nav-bar>
    <!-- #endif -->
    <view :style="{ 'padding-bottom': '54px', transform: messageBottom }"
      class="flex1 flex-column row-gap-10 margin-vertical-10">
      <view class="flex-column center row-gap-10 padding-bottom-10">
        <u-avatar :src="globalIcon.headPortrait"></u-avatar>
        <text class="font700">{{ user.full_name }}</text>
        <text class="font700">{{ user.username }} - instagram</text>
        <text>{{ user.edge_followed_by }}位粉丝</text>
        <text>{{ user.edge_owner_to_timeline_media }}篇帖子</text>
        <view class="bg-gray padding10 br-10" @click="goInfo">查看主页</view>
      </view>
      <message-item v-for="(item, index) in messageList" :key="index" :orientation="true" :content="item.content"
        :src="item.src" :pichref="item.pichref"></message-item>
      <view id="nine"></view>
    </view>
    <view :class="['stick', 'w100', 'bg-white']" :style="{ bottom: inputBottom, position: position }">
      <u-input v-model="val" @confirm="confirm" ref="input" shape="" :adjustPosition="false" placeholder="请输入消息"
        :confirmHold="true">
        <u-icon @click="choseImage" slot="suffix" size="40" name="photo"></u-icon>
      </u-input>
    </view>
  </view>
</template>

<script>
import MessageItem from "./message-item.vue";
import Config from "@/common/config.js";
import { randId } from "@/utils/utils.js"
import { addMessage, getMessage } from "@/api/app/api.js"
export default {
  components: {
    MessageItem,
  },
  data() {
    return {
      fans: 0,
      edge: 0,
      username: "",
      fullname: "",
      inputBottom: 0,
      height: "0px",
      paddingBottom: 54,
      messageBottom: 0,
      isStick: true,
      position: "fixed",
      val: "",
      messageList: [],
      user: {}
    };
  },
  onReady() {
    setTimeout(() => {
      wx.pageScrollTo({
        selector: "#nine",
        duration: 300,
        success(options) {
          console.log("options", options);
        },
        fail(err) {
          console.log("err", err);
        },
      });
    }, 100);
  },
  onLoad(option) {
    let channel = this.getOpenerEventChannel();
    channel.on("userinfo", (res) => {
      console.log('res', res)
      this.user = Object.assign({}, this.user, res.data);
      getMessage({
        openid: this.$store.getters.getUser.openid,
        page: 1,
        user: res.data.id
      }).then(res => {
        this.messageList.push(...res.data)
      })
    })
    uni.onKeyboardHeightChange(this.keyboard);
  },
  computed: {
    wxUser() {
      return this.$store.getters.getUser;
    }
  },
  methods: {
    goInfo() {
      uni.navigateBack()
    },
    confirm(val) {
      let info = {
        content: val,
        type: "text",
        src: Config.cloud_url + this.wxUser.avatar,
        createAt: +new Date(),
        state: "send",
        messageId: randId(20),
        openid: this.wxUser.openid,
        user: this.user.id,
      };
      addMessage(info).then(res => {
        this.messageList.push(info);
        this.val = "";
      }).catch(err => {
        console.log('err', err)
        wx.showToast({
          title: '发送失败',
          icon: 'error',
          duration: 1000
        })
      })
    },
    keyboard(res) {
      // 键盘
      let that = this;

      if (res.inputId === undefined) {
        if (res.height !== 0) {
          that.position = "relative";
          if (this.messageList.length > 4) {
            that.messageBottom = "translateY(-" + res.height + "px)";
          }
          wx.pageScrollTo({
            selector: "#nine",
            duration: 300,
            success(result) {
              console.log("键盘事件");
              that.inputBottom = res.height * 2 - 30 + "rpx";
              that.position = "fixed";
            },
          });
        } else {
          that.inputBottom = res.height * 2 + "rpx";
          that.messageBottom = "translateY(0%)";
        }
      }
      this.height = res.height * 2 + "rpx";
      this.paddingBottom = 54 + res.height;
    },
    uploadMediaFile(path, tmp, info) {
      const fs = wx.getFileSystemManager();
      uni.uploadFile({
        url: 'https://www.roseannepark.love:8000/upload',
        filePath: path,
        name: 'file',
        formData: {
          filename: tmp[tmp.length - 1]
        },
        success: (res) => {
          info.pichref = "https://roseannepark.love/chat_img/" + tmp[tmp.length - 1]
          addMessage(info).then(res => {
            this.messageList.push(info);
          }).catch(err => {
            console.log('err', err)
            wx.showToast({
              title: '图片发送失败',
              icon: 'error',
              duration: 1500
            })
          })
        },
        fail:(err)=>{
          console.log(err)
        }
      })
    },
    choseImage() {
      uni.chooseMedia({
        count: 1,
        mediaType: ["image"],
        sourceType: ["album", "camera"],
        success: (files) => {
          console.log(files);
          let path = files.tempFiles[0].tempFilePath;
          let info = {
            content: "",
            type: "image",
            src: Config.cloud_url + this.wxUser.avatar,
            createAt: +new Date(),
            state: "send",
            messageId: randId(20),
            openid: this.wxUser.openid,
            user: this.user.id,
            pichref: path
          };
          let tmp = path.split("/");
          this.uploadMediaFile(path, tmp, info)
        },
        fail(err) {
          console.log("错误", err);
        },
      });
    },
    takePhoto() {
      uni.chooseImage({
        count: 1,
        sourceType: ["camera"],
        success(files) {
          console.log(files);
        },
        fail(err) {
          console.log("错误", err);
        },
      });
    },
    goBack() {
      uni.navigateBack({});
    },
  },
  beforeDestroy() {
    uni.offKeyboardHeightChange(this.keyboard);
  },
};
</script>

<style lang="scss" scoped>
.flex-column ::v-deep .u-input {
  background-color: #ebebeb;
}

.test {
  transform: translateY(-50%);
}

#nine {
  width: 100%;
  height: 10px;
}
</style>
